package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    //通过定时任务每分钟检查一次是否存在支付超时订单（下单后超过15分钟仍未支付则判定为支付超时订单）
    // 如果存在则修改订单状态为“已取消”
    @Scheduled(cron = "0 * * * * ?")
    public void processOvertimeOrder(){
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> orderList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);

        if (orderList != null && orderList.size() > 0) {
            for(Orders order:orderList){
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason(MessageConstant.PAID_TIME_OUT);
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

    //通过定时任务每天凌晨1点检查一次是否存在“派送中”的订单（不查询最近一小时的订单
    // 如果存在则修改订单状态为“已完成”
    //@Scheduled(cron = "0 0 1 * * ?")
    @Scheduled(cron = "0 13 13 * * ?") //测试用
    public void processDeliveryOrder(){
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> orderList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);

        if (orderList != null && orderList.size() > 0) {
            for(Orders order:orderList){
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
